package cn.declare.interceptors;

import cn.declare.utils.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.SignatureException;
import org.apache.ibatis.ognl.TokenMgrError;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Author：葛鑫
 * JWT token 拦截器
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        String token = request.getHeader("token");

        System.out.println("=======================");
        System.out.println(token);

        try{
            Jwt jwt = JWTUtil.checkToken(token);//验证令牌
            return true;
        }catch (SignatureException e){
            e.printStackTrace();
            map.put("msg","签名无效！");
        }catch (TokenMgrError e){
            e.printStackTrace();
            map.put("msg","token过期！");
        }catch (ArithmeticException e){
            map.put("msg","token算法不一致！");
            e.printStackTrace();
        }catch (Exception e){
            map.put("msg","token无效！！");
            e.printStackTrace();
        }
        map.put("state",false);//设置状态
        //将map 转为json jackson
        String json=new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
